export default {
    // 为当前模块开启命名
    namespaced: true,

    state: () => ({
        // 购物车属性
        // [goods_name, goods_price, goods_state, goods_id, goods_count, goods_small_logo]
        cart: JSON.parse(uni.getStorageSync('cart') || '[]')
    }),

    mutations: {
        // 增加购物车
        addToCart(state, goods) {
            const findResult = state.cart.find((x) => x.goods_id === goods.goods_id)

            if (!findResult) {
                state.cart.push(goods)
            } else {
                findResult.goods_count++
            }

            this.commit('m_cart/saveToStorage')
        },
        // 修改商品是否选中状态
        changeState(state, goods_id) {
            const findResult = state.cart.find(x => x.goods_id === goods_id)

            findResult.goods_state = !findResult.goods_state
            this.commit('m_cart/saveToStorage')
        },
        // 修改商品数量
        changeCount(state, goods) {
            const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
            findResult.goods_count = goods.goods_count
            this.commit('m_cart/saveToStorage')
        },
        // 删除商品
        removeGoodsById(state, goods_id) {
            state.cart = state.cart.filter(x => x.goods_id !== goods_id)
            this.commit('m_cart/saveToStorage')
        },
        // 是否全选状态
        checkedAllState(state, checkAll) {

            state.cart.forEach(x => x.goods_state = checkAll)

        },
        // 存储到本地Storage
        saveToStorage(state) {
            uni.setStorageSync('cart', JSON.stringify(state.cart))
        },


    },

    getters: {
        // 购物车商品总数
        total(state) {
            let num = 0
            state.cart.forEach(goods => {
                num = num + goods.goods_count
            })
            return num
        },
        // 商品被选中数量
        checkedCount(state) {
            // let num = 0
            // state.cart.forEach(goods => {
            //     if (goods.goods_state)
            //         num += goods.goods_count
            // })
            // return num
            return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count, 0)
        },
        // 被选中商品总价格
        totalPrice(state) {
            // let total = 0
            // state.cart.forEach(goods => {
            //     if (goods.goods_state)
            //         total += (goods.goods_count * goods.goods_price)
            // })
            // return total.toFixed(2)
            const total = state.cart.filter(x => x.goods_state).reduce((total, item) => total += (item.goods_count * item.goods_price), 0)
            return total.toFixed(2)
        }

    }
}